import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import moment from 'moment';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import dataTime from '../../../utils/dataTime';
import { FormattedMessage } from 'umi-plugin-react/locale';
import download from '@/utils/download';

import UpDownCharacter from '../../../modules/UpDownCharacter';
import { Row, Col, Card, Icon, Table, Form, Spin, Modal, Button, message, Tabs, DatePicker, Select, Input, Tooltip, Drawer } from 'antd';
import styles from "./index.less";
import EditQa from '../../KnowledgeManagement/Overview/editQa';
const TabPane = Tabs.TabPane
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const Option = Select.Option;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_8lpmy5tq6hn.js', // 在 iconfont.cn 上生成
});
@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['waitingLearningIssue/fetch'],
}))

class UnknownProblem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loginjqr: false,
      logins: true,
      qaListTable: [],
      total2: '',
      knowledgeList: [],
      upDownDate: [],
      total: '',
      beginTime: '',
      overTime: '',
      total: '',
      login: false,
      dataSource: [],
      pageSize: 10,
      page: 1,
      selectedRowKeys: [],
      electa: 'time',
      electb: 'false',
      portJudge: true,
      break: false,
      field: 'q',
      question: '',
      evaluate: '',
      ignored: false,
      order: 'updateTime',
      asc: 'desc',
      zuid: '',
      shutRelevance: false,
      showModel1: false,
      numberRadio: '1',
      pageSizetwo: 10,
      pagetwo: 1,
      nodeId: '',
      nodeIdName: '所有分类',
      close: false,
      qaId: "",
      isUpdate: false,
      aALeng: '',
      glLeng: 10,
      qustzhuye: '',
      sort: '',
      unknownId:'',
      unresolvedId:''
    };
  }

  componentWillMount() {
    let sysTime = dataTime.formatDate(new Date().getTime()); // 初始时间
    let toTime = moment().subtract('days', 7).format('YYYY/MM/DD');
    this.setState({
      beginTime: toTime.replace(/\//g, '-'),
      overTime: sysTime.replace(/\//g, '-'),
    });
    console.log(sysTime);
  }

  // eslint-disable-next-line react/sort-comp
  fetch = (query, ignored, from, to, page, limit, order, sort) => {
    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'waitingLearningIssue/fetch',
        payload: { query, ignored, from, to, page, limit, order, sort },
        callback: res => {
          console.log('未知问题 列表', res);
          let temp = res.list
          temp.map((item, index) => item['key'] = index)
          this.props.totala(Number(res.total))
          this.setState({
            dataSource: temp,
            selectedRowKeys: [],
            total: Number(res.total),
            selectedRows: null,
            login: false,
            logins: true,
          })
        },
      });
    });
  }



  componentDidMount() {
    // this.fetch()
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
    this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)

  }

  upDate = (id) => {
    this.setState({ loginjqr: true })
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'waitingLearningIssue/fetchd',
      payload: { statChatId: id },
      callback: res => {
        console.log('上下文', res)
        if (res.list) {
          this.setState({
            upDownDate: res.list,
            loginjqr: false
          })
        } else {
          this.setState({
            upDownDate: [1],
            loginjqr: false
          })
        }
      },
    });
  }

  // 上下文组件回调函数
  handleSubUpDwonDate = (val) => {
    console.log(val)
    setTimeout(() => {
      this.upDate(val.lastChatId)
    }, 1)
  }

  // 获取关联列表数据
  AnswerRelevance = (question, field, query, page = 1, pageSize = 10) => {
    this.setState({
      logins: true
    })
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'waitingLearningIssue/fetchz',
      payload: { robotId: currentUser.robotId, question, field, query, page, limit: pageSize },
      callback: res => {
        console.log(res)
        let aA = res.suggestList
        let bB = res.qaList
        let aALeng = res.suggestList.length
        let bBLeng = res.qaList.length
        console.log(Number(aALeng + bBLeng))
        const total = [...aA, ...bB]
        total.map((item, index) => {
          item['key'] = index
          // item['time'] = Number(item.updateTime)
        })
        this.setState({
          total2: Number(res.total),
          qaListTable: total,
          logins: false,
          aALeng: aALeng,
          glLeng: Number(aALeng + bBLeng),
        })
      },
    });
  }

  // 搜索内容
  onFrom = (val) => {
    console.log('fu', val)
    this.setState({
      pagetwo: 1,
      query: val
    }, () => {
      if (val === '') {
        this.AnswerRelevance(
          this.state.question,
          this.state.field,
          this.state.query,
          1,
          this.state.glLeng)
      } else {
        this.AnswerRelevance(
          val,
          this.state.field,
          this.state.query,
          1,
          this.state.glLeng)
      }
    })
  }

  // 搜索问题
  onFromA = (val) => {
    console.log('fu', val)
    let text;
    if (val === '1') {
      text = 'q'
    }
    if (val === '2') {
      text = 'a'
    }
    this.setState({
      pagetwo: 1,
      field: text
    })
    setTimeout(() => {
      this.AnswerRelevance(
        this.state.question,
        this.state.field,
        this.state.query,
        1,
        this.state.glLeng)
    })
  }


  handleSubmitComment = (current) => {
    console.log('tcx', current, typeof (current))
    this.setState({ pagetwo: current })
    this.AnswerRelevance(
      this.state.question,
      this.state.field,
      this.state.query,
      current,
      this.state.glLeng
    )
  }



  callback = (key) => {
    console.log(key);
  }

  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    this.setState({
      beginTime: dateString[0].replace(/\//g, '-'),
      overTime: dateString[1].replace(/\//g, '-'),
    });
    console.log(date, dateString);
  };

  // 查看
  handleSubmit = () => {
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    // let usercz = this.props.form.resetFields();// 重置表单数据
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log(userInfo)
        this.setState({
          seek: userInfo.seek,
        })
        let a = ''
        if (userInfo.lose === 'true') {
          a = true
          this.setState({ electb: 'true', portJudge: false, break: true, page: 1 }, () => {
            const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
            this.fetch(seek, true, beginTime, overTime, page, pageSize, order, asc)
          })
          console.log(this.state.electb)
          // this.fetch(userInfo.seek, userInfo.evaluate, a, this.state.beginTime, this.state.overTime, '', '')

        } else if (userInfo.lose === 'false') {
          a = false
          this.setState({ electb: 'false', portJudge: true, break: false, page: 1 }, () => {
            const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
            this.fetch(seek, false, beginTime, overTime, page, pageSize, order, asc)
          })
          console.log(this.state.electb)
          // this.fetch(userInfo.seek, userInfo.evaluate, a, this.state.beginTime, this.state.overTime, '', '')

        }
      }
    })
  }


  newlyAdded = (row) => {
    console.log(row)
    this.setState({
      qaId: Array(row.question.replace(/<.*?>/g,"")),
      unknownId:row.id
    }, () => {
      this.setState({ close: true })
      console.log(this.state.unknownId,'新增id')
    })
  }

  onClose = () => {
    this.setState({
      close: false,
      // qaId: '',
      // isUpdate: true
    }, () => {
      const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
      this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)
    });
  };

  ignore = (row) => {
    console.log(row)


    let its = []
    its.push(row.id)
    console.log(its)
    const { dispatch } = this.props;
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'waitingLearningIssue/fetchc',
        payload: { unknowIds: its, ignored: this.state.portJudge },
        callback: res => {
          console.log('单个忽略', res);
          if (res.code === 0) {
            message['success'](`${res.msg}`)

            // this.fetch(this.state.seek, this.state.evaluate, this.state.break, this.state.beginTime, this.state.overTime, '', '')

            this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)

          }
        },
      });
    });

  }

  recovery = (row) => {
    console.log(row)
    let its = []
    its.push(row.id)
    console.log(its)
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'waitingLearningIssue/fetchc',
        payload: { unknowIds: its, ignored: this.state.portJudge },
        callback: res => {
          console.log('单个忽略', res);
          if (res.code === 0) {
            message['success'](`${res.msg}`)

            // this.fetch(this.state.seek, this.state.evaluate, this.state.break, this.state.beginTime, this.state.overTime, '', '')

            this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)

          }
        },
      });
    });
  }

  zuid = (text) => {
    console.log(text)
    this.setState({ zuid: text })
  }


  handleDelete = (item) => {
    console.log('item', item)
    this.setState({ shutRelevance: false })
    const { dispatch, currentUser } = this.props;
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
    dispatch({
      type: 'waitingLearningIssue/dcexport',
      payload: { qaId: item.sid, type: 0, targetId: this.state.zuid },
      callback: res => {
        if (res.code === 0) {
          message.success('执行成功！');
          this.setState({ showModel1: false })
          this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)
        }
        console.log('关联知识点', res)

      },
    });
  }

  setClassName = (record, index) => {
    return (index < this.state.aALeng ? styles.red : '')
  }

  down = () => {
    const { dispatch } = this.props;
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
    let userInfo = this.props.form.getFieldsValue();// 获取数据

    const data = { from: beginTime, ignored: userInfo.lose, order: order, sort: asc, to: overTime, query: userInfo.seek }

    dispatch({
      type: 'waitingLearningIssue/exportWz',
      payload: data,
      callback: (res) => {
        console.log(res)
        let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
        download.byBlob(res.fileBlob, filename)
      }
    });
  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const columns1 = [
      {
        title: '问题',
        dataIndex: 'question',
        width: 'calc(30vw)',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{item}</span>
            </div>
          );
        },
      },
      {
        title: '分类',
        dataIndex: 'category',
        width: 'calc(30vw)',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{item}</span>
            </div>
          );
        },
      },
      {
        title: '操作',
        render: (text, item) => {
          return <div className={styles.pb}>
            <div className={styles.buttongl} onClick={(text) => { this.handleDelete(item) }}>
              <span><Icon size="small" type="link" style={{ marginRight: 5 }} /></span>
              <span>关联</span>
            </div>
          </div>
        }
      },
    ]
    return (
      <Suspense fallback={<PageLoading />}>
        <div style={{ padding: '0px 20px 0px 30px' }}>
          <div style={{ marginBottom: 20 }} className={styles.fromColumn}>
            {
              this.state.electb === 'false' ? <span className='zdyButtonA'><Button style={{ marginTop: 10 }} onClick={this.handleRelete} type='primary' icon="eye-invisible">批量忽略</Button></span> : <span className='zdyButtonA'><Button style={{ marginTop: 5 }} onClick={this.handleRelete} type='primary' icon="eye-invisible">批量恢复</Button></span>
            }

            <div >
              <Form className={styles.buttonA} layout="inline">
                <FormItem>
                  <RangePicker
                    onChange={this.onChange}
                    style={{ width: 220 }}
                    defaultValue={[
                      moment(this.state.beginTime, dateFormat),
                      moment(this.state.overTime, dateFormat),
                    ]}
                    format={dateFormat}
                  />
                </FormItem>
                <FormItem>
                  {getFieldDecorator('lose', {
                    initialValue: this.state.electb,// 初始值
                  })(
                    <Select style={{ width: 130 }}>
                      <Option value='false'>未忽略</Option>
                      <Option value='true'>已忽略</Option>
                    </Select>
                  )
                  }
                </FormItem>
                <FormItem>
                  {getFieldDecorator('seek', {
                    initialValue: '',// 初始值
                  })(
                    <Input
                      onPressEnter={this.handleSubmit}
                      placeholder="请输入搜索内容"
                    />
                  )
                  }
                </FormItem>
                <FormItem className='buttonYs'>
                  <Button onClick={this.handleSubmit} icon="search">
                    搜索
                  </Button>
                </FormItem>
                <FormItem className='buttonYs'>
                  <Button onClick={this.down} icon="arrow-down">
                    {/* 下载 */}
                    下载
                  </Button>
                </FormItem>
              </Form>
            </div>
          </div>
          {this.lessdata()}
          <Modal
            style={{ top: 60 }}
            width={'calc( 70vw)'}
            className={styles.overa}
            title='添加关联知识点'
            visible={this.state.showModel1}
            footer={null}
            onCancel={() => {
              this.setState({
                showModel1: false
              })
            }}
            onOk={() => { // 确定方法不开出去
              this.setState({
                showModel1: false
              })
            }}
          >

            <Form layout="inline" style={{ paddingBottom: 20 }}>
              <FormItem style={{ marginLeft: 20 }}>

                <Select
                  defaultValue={this.state.numberRadio}
                  style={{ width: 160 }}
                  onChange={this.onFromA}
                >
                  <Option value='1'>搜索问题</Option>
                  <Option value='2'>搜索答案</Option>
                </Select>
              </FormItem>
              <FormItem >
                {getFieldDecorator('businessName', {
                  initialValue: '',
                })(
                  <Search
                    placeholder="请输入搜索内容"
                    onSearch={value => {
                      this.onFrom(value)
                    }}
                    style={{ width: 320 }}
                  />
                )}
              </FormItem>
            </Form>
            <Spin spinning={this.state.logins}>
              <Table
                rowClassName={this.setClassName}
                className={styles.over}
                //  bordered
                columns={columns1}
                dataSource={this.state.qaListTable}
                pagination={{  // 分页
                  total: this.state.total2, // 数据总数量
                  pageSize: this.state.glLeng,  // 显示几条一页
                  current: this.state.pagetwo, // 当前页
                  showQuickJumper: true,
                  onChange: this.handleSubmitComment,
                  onShowSizeChange: this.handleSubmitComments
                }}
              />
            </Spin>
          </Modal>
          <Drawer
            title={<FormattedMessage id="app.overView.editQa" />}
            placement="right"
            closable={false}
            onClose={this.onClose}
            visible={this.state.close}
            width={800}
            destroyOnClose
          >

            <EditQa unknownId={this.state.unknownId} questions={this.state.qaId} onClose={this.onClose} />
          </Drawer>

        </div>

      </Suspense>
    );
  }

  handleChange = (pagination, filters, sorter) => {
    console.log(pagination, filters, sorter)
    if (sorter.columnKey === 'count') {
      if (sorter.order === "ascend") { // 升序
        this.setState({ order: 'count', asc: 'asc' })
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'count', 'asc')
      }
      if (sorter.order === "descend") { // 降序
        this.setState({ order: 'count', asc: 'desc' })
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'count', 'desc')
      }
      this.setState({
        sortOrder: sorter.order,
        evaluate: 'count'
      })
    }
    if (sorter.columnKey === "updateTime") {
      if (sorter.order === "ascend") { // 升序
        this.setState({ order: 'updateTime', asc: 'asc' })
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'updateTime', 'asc')
      }
      if (sorter.order === "descend") { // 降序
        this.setState({ order: 'updateTime', asc: 'desc' })
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'updateTime', 'desc')
      }
      this.setState({
        sortOrder: sorter.order,
        evaluate: 'count'
      })
    }

  }




  lessdata = () => {


    const { selectedRowKeys } = this.state
    // 多选
    const rowCheckSelection = {
      type: 'checkbox',
      selectedRowKeys, //告诉插件我们点击的哪一行
      onChange: (selectedRowKeys, selectedRows) => {
        console.log('1', selectedRowKeys, '2', selectedRows)
        this.setState({
          selectedRowKeys,
          selectedRows: selectedRows
        })
      }
    }
    const columns = [
      {
        title: `未知问题`,
        width: 'calc(20vw)',
        dataIndex: 'question',
        render(item) {
          return (
            // <div className={styles.wtbj}>{item}</div>
            <div className={styles.wtbj} dangerouslySetInnerHTML={{ __html: item }}></div>
          )
        }
      },
      {
        title: '询问次数',
        width: 'calc(15vw)',
        dataIndex: 'count',
        sorter: (a, b) => { },
        // sortOrder:this.state.sortOrder
      },
      {
        title: '最近询问时间',
        width: 'calc(20vw)',
        dataIndex: 'updateTime',
        sorter: (a, b) => { },
        // sorter: (a, b) => a.createTime - b.createTime,
        render: (updateTime) => {
          return moment(Number(updateTime)).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        title: '操作',
        width: 'calc(18vw)',
        render: (text, row) => {
          return <div className={styles.wt}>
            <div className='zdyButtonA'>
              <Button
                type='primary'
                icon='link'
                size="small"
                onClick={() => this.handleOpen(row)}>
                关联
              </Button>
            </div>
            <div className='zdyButtonA'>
              <Button type="primary" htmlType='button' size='small' icon="plus" className={styles.processBtn} onClick={() => this.newlyAdded(row)}>
                新增
              </Button>
            </div>
            {
              this.state.electb === 'false' ? <div className='zdyButtonA'><Button type="primary" icon="eye-invisible" htmlType='button' size='small' className={styles.processBtn} onClick={() => this.ignore(row)}>忽略</Button> </div> : ''
            }
            <UpDownCharacter
              text={text}
              name='上下文'
              icons='bars'
              title='聊天上下文'
              updowndate={this.state.upDownDate}
              onSubmitA={this.handleSubUpDwonDate}
              loginjqr={this.state.loginjqr}
              empty={this.empty}
            />
            {
              this.state.electb === 'false' ? '' : <div className='zdyButtonA'><Button type="primary" htmlType='button' size='small' className={styles.processBtn} onClick={() => this.recovery(row)}><MyIcon type="icon-huifu" />恢复</Button> </div>
            }

          </div>;
        },
      }
    ]
    return (
      <Spin spinning={this.state.login}>
        <Table
          // className='zdyTable'
          rowSelection={rowCheckSelection}
          style={{ padding: '0px 0px 0px 0px' }}
          columns={columns}
          dataSource={this.state.dataSource}//数据
          onChange={this.handleChange}
          pagination={{  // 分页
            total: Number(this.state.total),
            pageSize: this.state.pageSize,  // 显示几条一页
            current: this.state.page, // 当前页
            showSizeChanger: true,  // 是否显示可以设置几条一页的选项
            showQuickJumper: true,
            onChange: this.onChangeA,
            onShowSizeChange: this.onShowSizeChangeA
          }}
        />
      </Spin>
    )
  }

  onChangeA = (val) => { // 页数选择
    console.log(val)
    this.setState({ page: val }, () => {
      // this.setState({ order: 'count', sort: 'asc' })
      setTimeout(() => {
        const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
        this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)
        // this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, this.setState.order,this.setState.sort)
      }, 1)
    })
  }

  // 每页显示多少条数据
  onShowSizeChangeA = (current, pageSize) => {
    console.log('1', current, '2', pageSize);
    this.setState({ pageSize: pageSize, page: current }, () => {
      const { seek, beginTime, overTime, pageSize, page, order, asc } = this.state
      this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)
    })
    // this.fetch(this.state.seek, this.state.evaluate, this.state.break, this.state.beginTime, this.state.overTime, current, pageSize)
  }

  handleRelete = () => {
    let rows = this.state.selectedRows
    if (this.state.break === false) { // 忽略
      if (rows) {
        let its = []
        rows.map((item) => {
          its.push(item.id)
        })
        console.log(its)

        Modal['confirm']({
          title: '忽略问题',
          content: '确定忽略吗？',
          okText: "确认",
          cancelText: "取消",
          onOk: () => {
            const { dispatch } = this.props;
            const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
            this.reqRef = requestAnimationFrame(() => {
              dispatch({
                type: 'waitingLearningIssue/fetchc',
                payload: { unknowIds: its, ignored: this.state.portJudge },
                callback: res => {
                  console.log('批量删除恢复', res);
                  if (res.code === 0) {
                    message['success'](`${res.msg}`)
                    this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)
                  }
                  if (res.status === '1') {
                    message['error'](`${res.msg}`)
                  }
                },
              });
            });
          },
          onCancel() {
            console.log('onCancel')
          }
        })
      } else {
        message['error']('您还没有选择！')
      }
    } else if (this.state.break === true) {
      if (rows) {
        let its = []
        rows.map((item) => {
          its.push(item.id)
        })
        console.log(its)
        const { dispatch } = this.props;
        const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'waitingLearningIssue/fetchc',
            payload: { unknowIds: its, ignored: this.state.portJudge },
            callback: res => {
              console.log('批量恢复', res);
              if (res.code === 0) {
                message['success'](`${res.msg}`)

                // this.fetch(this.state.seek, this.state.evaluate, this.state.break, this.state.beginTime, this.state.overTime, '', '')

                this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc)
              }
              if (res.status === '1') {
                message['error'](`${res.msg}`)
              }
            },
          });
        });
      } else {
        message['error']('您还没有选择！')
      }
    }
  }

  empty = () => {
    this.setState({ upDownDate: [] })
  }

  //  关联方法
  handleOpen = (row) => {
    this.props.form.setFields({ "businessName": "" })
    console.log(row)
    this.setState({ question: row.question, query: '' }, () => {
      this.AnswerRelevance(
        this.state.question,
        this.state.field,
        this.state.query,
        1,
        10)
      this.setState({ showModel1: true, zuid: row.id })
    })

  }

}
export default connect(({ user }) => ({ // 全局数据 portJudge
  currentUser: user.currentUser,
}))(Form.create()(UnknownProblem));
